package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
//import java.util.List;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryAllType() {
        //1.在redis中查询所有的shopType
        List<String> shopTypeJson = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, stringRedisTemplate.opsForList().size(CACHE_SHOP_TYPE_KEY));

//        2.判断redis中存在吗
        if (shopTypeJson != null && shopTypeJson.size() != 0){
            //3.存在就返回
            ArrayList<ShopType> shopTypes = new ArrayList<>();
            for (int i = 0; i < shopTypeJson.size(); i++) {
                shopTypes.add(JSONUtil.toBean(shopTypeJson.get(i),ShopType.class));
            }


            return Result.ok(shopTypes);
        }


        //4.不存在就在数据库中查询所有的shopType
        List<ShopType> typeList = query().orderByAsc("sort").list();


//      5.  判断数据库中查询出来的的shopType存在不
        if (typeList == null){
//        6.typeList为空 就报错
            return Result.fail("商铺 分类 类型 找不到异常");

        }

//        7.shopType存在,保存到redis中

//        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE_KEY, String.valueOf(typeList));
        ArrayList<String> shopTypeJsonList = new ArrayList<>();

        for (int i = 0; i <typeList.size() ; i++) {
            shopTypeJsonList.add(JSONUtil.toJsonStr(typeList.get(i)));
        }


        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE_KEY,shopTypeJsonList);
        stringRedisTemplate.expire(CACHE_SHOP_TYPE_KEY,CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
//        8.返回shopType
        return Result.ok(typeList);
    }
}
